#include "handler_pool.h"
#include "file_handler.h"

#include <cstdlib>


bool THandlerPool::Init( unsigned int poolSize
                       , TConnectionManager& connections
                       , const std::string& path
                       , unsigned int ioBufferSize )
{
    unsigned int    handlerNum  =   0;
    bool            result      =   true;

    while((result) && (handlerNum != poolSize)) {
        TStaticFileHandler* handler =    new TStaticFileHandler(connections);
        result  =   handler->Init(path, ioBufferSize);

        if (!result) {
            continue;
        }

        Handlers.push_back(handler);


        pthread_t*  thread      =   static_cast<pthread_t*>(malloc(sizeof(pthread_t)));
        int         thread_res  =   pthread_create( thread
                                                  , NULL
                                                  , TConnectionHandler::Run
                                                  , handler );
        result  =   (thread_res == 0);

        if (result) {
            Threads.push_back(thread);
        }
        ++handlerNum;
    }

    return result;
}

void THandlerPool::Stop()
{
    for (unsigned int threadNum = 0; threadNum != Threads.size(); ++threadNum) {
        pthread_t*  thread(Threads[threadNum]);
        if (thread) {
            pthread_join(*thread, NULL);
        }
    }
}

THandlerPool::~THandlerPool()
{
    Stop();
    for (unsigned int handlerNum = 0; handlerNum != Handlers.size(); ++ handlerNum) {
        delete Handlers[handlerNum];
    }

    for (unsigned int threadNum = 0; threadNum != Threads.size(); ++threadNum) {
        pthread_t*  thread(Threads[threadNum]);
        if (thread) {
            free(thread);
        }
    }
}
